from app import create_app, db
from app.models import MonitorPoint, AlarmRule, AlarmRecord
from datetime import datetime, timedelta
import random

def create_alarm_data():
    app = create_app()
    with app.app_context():
        # 清除现有的报警数据
        AlarmRecord.query.delete()
        AlarmRule.query.delete()
        
        # 获取所有监控点
        points = MonitorPoint.query.all()
        if not points:
            print("请先创建监控点数据！")
            return
        
        # 为每个监控点创建报警规则
        rules = []
        for point in points:
            # 溶解氧规则
            rules.append(AlarmRule(
                point_id=point.id,
                parameter='dissolved_oxygen',
                min_value=4.0,
                max_value=8.0,
                level='warning',
                enabled=True
            ))
            
            # pH值规则
            rules.append(AlarmRule(
                point_id=point.id,
                parameter='ph_value',
                min_value=6.5,
                max_value=8.5,
                level='danger',
                enabled=True
            ))
            
            # 温度规则
            rules.append(AlarmRule(
                point_id=point.id,
                parameter='temperature',
                min_value=20.0,
                max_value=28.0,
                level='warning',
                enabled=True
            ))
            
            # 氨氮规则
            rules.append(AlarmRule(
                point_id=point.id,
                parameter='ammonia_nitrogen',
                min_value=0.1,
                max_value=0.5,
                level='danger',
                enabled=True
            ))
            
            # 浊度规则
            rules.append(AlarmRule(
                point_id=point.id,
                parameter='turbidity',
                min_value=10.0,
                max_value=30.0,
                level='warning',
                enabled=True
            ))
        
        # 保存规则
        for rule in rules:
            db.session.add(rule)
        db.session.commit()
        
        # 创建报警记录
        now = datetime.utcnow()
        parameter_units = {
            'dissolved_oxygen': 'mg/L',
            'ph_value': '',
            'temperature': '℃',
            'ammonia_nitrogen': 'mg/L',
            'turbidity': 'NTU'
        }
        
        # 创建一些活跃的报警
        for _ in range(5):
            rule = random.choice(rules)
            if rule.min_value is not None and rule.max_value is not None:
                # 随机生成超出范围的值
                if random.choice([True, False]):
                    value = rule.min_value - random.uniform(0.5, 2.0)
                    threshold_desc = f"低于最小值 {rule.min_value} {parameter_units.get(rule.parameter, '')}"
                else:
                    value = rule.max_value + random.uniform(0.5, 2.0)
                    threshold_desc = f"超过最大值 {rule.max_value} {parameter_units.get(rule.parameter, '')}"
                
                alarm = AlarmRecord(
                    point_id=rule.point_id,
                    rule_id=rule.id,
                    parameter=rule.parameter,
                    current_value=round(value, 2),
                    threshold=threshold_desc,
                    level=rule.level,
                    status='active',
                    created_at=now - timedelta(minutes=random.randint(5, 120))
                )
                db.session.add(alarm)
        
        # 创建一些已解决的历史报警
        for _ in range(20):
            rule = random.choice(rules)
            if rule.min_value is not None and rule.max_value is not None:
                if random.choice([True, False]):
                    value = rule.min_value - random.uniform(0.5, 2.0)
                    threshold_desc = f"低于最小值 {rule.min_value} {parameter_units.get(rule.parameter, '')}"
                else:
                    value = rule.max_value + random.uniform(0.5, 2.0)
                    threshold_desc = f"超过最大值 {rule.max_value} {parameter_units.get(rule.parameter, '')}"
                
                created_time = now - timedelta(days=random.randint(1, 30))
                alarm = AlarmRecord(
                    point_id=rule.point_id,
                    rule_id=rule.id,
                    parameter=rule.parameter,
                    current_value=round(value, 2),
                    threshold=threshold_desc,
                    level=rule.level,
                    status='resolved',
                    created_at=created_time,
                    resolved_at=created_time + timedelta(minutes=random.randint(10, 120))
                )
                db.session.add(alarm)
        
        db.session.commit()
        
        # 打印统计信息
        rules_count = AlarmRule.query.count()
        active_alarms = AlarmRecord.query.filter_by(status='active').count()
        resolved_alarms = AlarmRecord.query.filter_by(status='resolved').count()
        
        print('报警测试数据创建成功！')
        print(f'已创建 {rules_count} 条报警规则')
        print(f'已创建 {active_alarms} 条活跃报警')
        print(f'已创建 {resolved_alarms} 条历史报警')

if __name__ == '__main__':
    create_alarm_data() 